package org.csu.small.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.csu.small.common.Constant;
import org.csu.small.common.UniformResponse;
import org.csu.small.entity.User;
import org.csu.small.persistence.UserMapper;
import org.csu.small.service.IUserService;
import org.csu.small.utils.MD5Util;
import org.csu.small.utils.MessageUtil;
import org.csu.small.utils.TokenCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author Rambo
 * @date 2020-06-08 9:24
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UniformResponse<User> manageLogin(String loginString, String password) {
        String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";/*验证邮箱*/
        String ph = "^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0,5-9]))\\d{8}$";  /*java用验证手机号*/
        String queryColumn = Constant.USERNAME;
        if(loginString.matches(ph)) {
            queryColumn = Constant.PHONE;

        }else if(loginString.matches(em)) {
            queryColumn = Constant.EMAIL;
        }

        int rows = userMapper.selectCount(Wrappers.<User>query().eq(queryColumn,loginString).eq("role",Constant.Role.ADMIN));

        if(rows == 0){
            return UniformResponse.createForErrorMessage("用户不存在");
        }
        String md5Password = MD5Util.md5Encrypt32Upper(password);
        User user = userMapper.selectOne(Wrappers.<User>query().eq(queryColumn,loginString).eq(Constant.PASSWORD,md5Password));
        if(user == null){
            return UniformResponse.createForErrorMessage("账户名与密码不匹配，请重新输入");
        }
        user.setPassword(StringUtils.EMPTY);
        return UniformResponse.createForSuccess("登录成功",user);
    }

    @Override
    public UniformResponse<User> login(String loginString, String password) {
        String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";/*验证邮箱*/
        String ph = "^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0,5-9]))\\d{8}$";  /*java用验证手机号*/
        String queryColumn = Constant.USERNAME;
        if(loginString.matches(ph)) {
            queryColumn = Constant.PHONE;

        }else if(loginString.matches(em)) {
            queryColumn = Constant.EMAIL;
        }

        int rows = userMapper.selectCount(Wrappers.<User>query().eq(queryColumn,loginString));

        if(rows == 0){
            return UniformResponse.createForErrorMessage("用户名不存在");
        }

        String md5Password = MD5Util.md5Encrypt32Upper(password);
        User user = userMapper.selectOne(Wrappers.<User>query().eq(queryColumn,loginString).eq(Constant.PASSWORD,md5Password).eq("role",Constant.Role.CUSTOMER));
        if(user == null){
            return UniformResponse.createForErrorMessage("账户名与密码不匹配，请重新输入");
        }
        user.setPassword(StringUtils.EMPTY);
        return UniformResponse.createForSuccess("登录成功",user);
    }

    @Override
    public UniformResponse<String> register(User user){
        int rows = userMapper.selectCount(Wrappers.<User>query().eq("username",user.getUsername()));
        if(rows > 0){
            return UniformResponse.createForErrorMessage("该用户名已存在");
        }
        rows = userMapper.selectCount(Wrappers.<User>query().eq("email",user.getEmail()));
        if(rows > 0){
            return UniformResponse.createForErrorMessage("该邮箱已存在");
        }
        rows = userMapper.selectCount(Wrappers.<User>query().eq("phone",user.getPhone()));
        if(rows > 0){
            return UniformResponse.createForErrorMessage("该手机号已存在");
        }
        user.setRole(Constant.Role.CUSTOMER);
        //密码MD5加密
        user.setPassword(MD5Util.md5Encrypt32Upper(user.getPassword()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setPoint(Constant.Point.ZERO);

        rows = userMapper.insert(user);
        if(rows == 0){
            return UniformResponse.createForErrorMessage("注册失败");
        }
        return UniformResponse.createForSuccessMessage("注册成功");
    }

    @Override
    public UniformResponse<String> checkField(String value, String type){
        if(StringUtils.isNoneBlank(type)){
            if(Constant.USERNAME.equals(type)){
                int rows = userMapper.selectCount(Wrappers.<User>query().eq("username",value));
                if (rows > 0 ){
                    return UniformResponse.createForErrorMessage("用户名已存在");
                }
            }
            if(Constant.EMAIL.equals(type)){
                int rows = userMapper.selectCount(Wrappers.<User>query().eq("email",value));
                if (rows > 0 ){
                    return UniformResponse.createForErrorMessage("email已存在");
                }
            }
            if(Constant.PHONE.equals(type)){
                int rows = userMapper.selectCount(Wrappers.<User>query().eq("phone",value));
                if (rows > 0 ){
                    return UniformResponse.createForErrorMessage("手机号已存在");
                }
            }
        }else{
            UniformResponse.createForErrorMessage("参数错误");
        }
        return UniformResponse.createForSuccessMessage("字段校验成功");
    }

    @Override
    public UniformResponse<String> sendCode(String phone) {
        //判断手机号符不符合规则
        //return UniformResponse.createForErrorMessage("手机号错误");
        String code = MessageUtil.generateCode();
        String messageId = phone + code;
        try {
            boolean isSuccess = MessageUtil.sendMessage(phone,code,messageId);
            if(isSuccess){
                TokenCacheUtil.setToken(phone,code);
                return UniformResponse.createForSuccess(code);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return UniformResponse.createForErrorMessage("短信发送失败");
    }

    @Override
    public UniformResponse<String> checkPhoneAndCode(String phone, String code) {
        if(code != null) {
            String cacheCode = TokenCacheUtil.getToken(phone);
            if(code.equals(cacheCode)){

                return UniformResponse.createForSuccess("验证通过");
            }
        }
        return UniformResponse.createForErrorMessage("验证码不正确");
    }

    @Override
    public UniformResponse<String> checkLoginString(String value, String type) {
        User user = null;
        if(StringUtils.isNoneBlank(type)){
            if(Constant.USERNAME.equals(type)){
                System.out.println(type+value);
                user = userMapper.selectOne(Wrappers.<User>query().eq("username",value));
                if (user == null ){
                    return UniformResponse.createForErrorMessage("用户名不存在");
                }
            }
            if(Constant.EMAIL.equals(type)){
                user = userMapper.selectOne(Wrappers.<User>query().eq("email",value));
                if (user == null){
                    return UniformResponse.createForErrorMessage("email不存在");
                }
            }
            if(Constant.PHONE.equals(type)){
                user = userMapper.selectOne(Wrappers.<User>query().eq("phone",value));
                if (user == null){
                    return UniformResponse.createForErrorMessage("手机号不存在");
                }
            }
        }else{
            UniformResponse.createForErrorMessage("登录名输入错误");
        }

        return UniformResponse.createForSuccess("登录名验证成功",user.getPhone());
    }

    @Override
    public UniformResponse<String> updateInfomation(User user, String username, String email) {

        UniformResponse<String> usernameResponse = checkField(username,Constant.USERNAME);
        if(!usernameResponse.isSuccess() && !username.equals(user.getUsername()) ){
            return UniformResponse.createForErrorMessage("用户名已存在");
        }
        UniformResponse<String> emailResponse = checkField(email,Constant.EMAIL);
        if(!emailResponse.isSuccess() && !email.equals(user.getEmail()) ){
            return UniformResponse.createForErrorMessage("邮箱已存在");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setEmail(email);
        userMapper.updateById(updateUser);
        return UniformResponse.createForSuccessMessage("更新个人信息成功");
    }

    @Override
    public UniformResponse<String> resetPasswordByPhone(String phone,String passwordNew) {

        String md5Password = MD5Util.md5Encrypt32Upper(passwordNew);
        User user = new User();
        user.setPassword(md5Password);
        int row = userMapper.update(user, Wrappers.<User>query().eq("phone",phone));
        if(row > 0){
            return UniformResponse.createForSuccess("修改密码成功");
        }
        return UniformResponse.createForErrorMessage("修改密码失败");
    }

    @Override
    public UniformResponse<String> resetPassword(User user, String passwordOld,String passwordNew) {
        String passwordOldString = MD5Util.md5Encrypt32Upper(passwordOld);
        int rows = userMapper.selectCount(Wrappers.<User>query().eq("phone",user.getPhone()).eq("password",passwordOldString));
        if (rows > 0 ){
            User updateUser = new User();
            updateUser.setPassword(MD5Util.md5Encrypt32Upper(passwordNew));
            userMapper.update(updateUser, Wrappers.<User>query().eq("phone",user.getPhone()));
            return UniformResponse.createForSuccessMessage("修改密码成功");
        }
        return UniformResponse.createForErrorMessage("原密码输入错误");
    }

    public boolean checkUsernameAndEmail(String value, String type) {
        int rows = userMapper.selectCount(Wrappers.<User>query().eq(type, value));
        return rows > 0;
    }

    @Override
    public UniformResponse<Object> getUserList(String keyword, int pageNum, int pageSize) {

        Page<User> result = new Page<>();
        result.setCurrent(pageNum);
        result.setSize(pageSize);

        QueryWrapper<User> query = new QueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)){
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
            query.like("username", keyword);
        }

        result = userMapper.selectPage(result, query);
        return UniformResponse.createForSuccess(result);
    }
}
